package com.taotao.health.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.core.domain.Result;
import com.taotao.common.redis.service.RedisService;
import com.taotao.common.security.utils.SecurityUtils;
import com.taotao.health.config.AliPayConfig;
import com.taotao.health.domain.AliPay;
import com.taotao.health.service.MedicalRecordService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付控制器
 */
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    private AliPayConfig aliPayConfig;

    @Autowired
    private MedicalRecordService medicalRecordService;


    @Autowired
    private RedisService redisService;


    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    /**
     * 创建支付订单
     */
    @GetMapping("/pay")
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {


//        // 获取当前用户ID并存储在订单号中
//        Long userId = SecurityUtils.getUserId();
//        System.out.println("创建订单时的用户ID: " + userId);
//
//        // 修改订单号格式，加入用户ID：H时间戳_医生ID_费用_用户ID
//        String newTraceNo = aliPay.getTraceNo() + "_" + userId;
//        aliPay.setTraceNo(newTraceNo);


        // 创建支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 创建支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());

        // 设置业务参数
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 生成支付表单
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 输出支付表单
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 支付回调通知
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            // 获取回调参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            // 获取订单号
            String traceNo = params.get("out_trade_no");

            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过，打印交易信息
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));

                try {
                    // 从订单号中提取信息（格式：H时间戳_医生ID_费用_用户ID）
                    String[] orderInfo = traceNo.split("_");
                    Long doctorId = Long.parseLong(orderInfo[1]);
                    BigDecimal registrationFee = new BigDecimal(orderInfo[2]);
                    Long patientId = Long.parseLong(orderInfo[3]);

                    // 创建就诊记录并获取自增ID
                    Long medicalRecordId = medicalRecordService.createMedicalRecord(doctorId, registrationFee, patientId);
                    //将id存入到redis中 流水号为key 自增id为value
                    redisService.redisTemplate.opsForValue().set(traceNo, medicalRecordId.toString());
                    System.out.println("创建就诊记录成功，ID: " + medicalRecordId);

                    // 构建响应数据
                    Map<String, Object> responseData = new HashMap<>();
                    responseData.put("code", 200);
                    responseData.put("message", "支付成功");
                    responseData.put("data", new HashMap<String, Object>() {{
                        put("medicalRecordId", medicalRecordId);
                        put("doctorId", doctorId);
                        put("patientId", patientId);
                        put("traceNo", traceNo);
                        put("status", "success");
                    }});

                    // 返回JSON响应
                    return new ObjectMapper().writeValueAsString(responseData);
                } catch (Exception e) {
                    System.err.println("处理支付回调失败: " + e.getMessage());
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("code", 500);
                    errorResponse.put("message", "处理支付回调失败");
                    errorResponse.put("error", e.getMessage());
                    return new ObjectMapper().writeValueAsString(errorResponse);
                }
            }
        }

        // 处理失败响应
        Map<String, Object> failResponse = new HashMap<>();
        failResponse.put("code", 400);
        failResponse.put("message", "支付验证失败");
        return new ObjectMapper().writeValueAsString(failResponse);
    }
}
